package com.bidevalution.business.function;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.StringUtils;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorDouble;
import com.googlecode.aviator.runtime.type.AviatorObject;
/**
 * 求平均值计算
 * @author daizhifeng   
 * @date 2019年10月10日 下午9:40:01 
 * @version V2.0
 */
public class AverageFunction extends AbstractFunction {
	private FunctionInitializer functionInitializer;
	private Logger logger = LogManager.getLogger(getClass());
	public AverageFunction(FunctionInitializer functionInitializer) {
		super();
		this.functionInitializer = functionInitializer;
	}
	/**
	 * 计算平均值
	 * <p>Description: </p>
	 * @param env
	 * @param arg1 值以逗号隔开
	 * @return
	 * @see com.googlecode.aviator.runtime.function.AbstractFunction#call(java.util.Map, com.googlecode.aviator.runtime.type.AviatorObject)
	 */
	@Override
	public AviatorObject call(Map<String, Object> env, AviatorObject arg1) {
		String paramValue = FunctionUtils.getStringValue(arg1, env);

		List<String> priceList = new LinkedList<String>(Arrays.asList(paramValue.split(",")));
		BigDecimal bigDecimal = new BigDecimal(0);
		for(String price:priceList) {
			if(!StringUtils.isEmpty(price)) {
				bigDecimal = bigDecimal.add(new BigDecimal(price));
			}
		}
		if(bigDecimal.compareTo(new BigDecimal(0))==0) {
			return new AviatorDouble(0) ;
		}
		Double result = bigDecimal.divide(new BigDecimal(priceList.size()),3, BigDecimal.ROUND_HALF_UP).doubleValue();
		logger.info("average:"+result);
		return new AviatorDouble(result);
	}

	@Override
	public String getName() {
		return "average";
	}

}
